module(...,package.seeall)

local mrg = {}

function getfdata(file,idx,unitlen)
	local f,rt = io.open(file,"rb")
	if not f then log.error("split.getfdata not open file err",file) return "" end
	if not f:seek("set",(idx-1)*unitlen) then log.error("split.getfdata seek err") return "" end
	rt = f:read(unitlen)
	f:close()
	return rt or ""
end

function getfinf(file,unitlen)
	local f = io.open(file,"rb")
	if not f then log.error("split.getfinf open file err",file) return 0 end
	local size = f:seek("end")
	if not size or size == 0 then log.error("split.getfinf seek err") return 0 end
	f:close()
	log.info("split.getfinf",size)
	return (size-1)/unitlen+1
end

local function append(pth,dat)
	local f = io.open(pth,"ab+")
	f:seek("end")
	f:write(dat)
	f:close()
end

local function clr(tag)
	local i
	if mrg[tag].dat then
		for i=1,#mrg[tag].dat do
			mrg[tag].dat[i] = nil
		end
	end
	mrg[tag].dat = nil
	mrg[tag] = nil
	log.info("split.clr")
end

local function timerfnc()
	local empty,k,v = true
	for k,v in pairs(mrg) do
		log.info("split.timerfnc1",#mrg,v.expire)
		if v.expire and v.expire>0 then
			v.expire = v.expire - 1
			if v.expire==0 then
				if v.pth then os.remove(v.pth) end
				clr(k)
			else
				empty = false
			end
		end
	end
	log.info("split.timerfnc2",empty)
	if empty then sys.timer_stop(timerfnc) end
end

function merge(tag,pth,total,cur,dat)
	if not tag then return end
	if not mrg[tag] then mrg[tag]={} end
	if not mrg[tag].pth then mrg[tag].pth = pth end
	if not mrg[tag].total then mrg[tag].total = total end
	if not mrg[tag].cur then mrg[tag].cur = 0 end
	if not mrg[tag].dat then mrg[tag].dat={} end	
	
	log.info("split.merge1",cur,mrg[tag].cur+1)
	
	if cur==mrg[tag].cur+1 then
		append(mrg[tag].pth,dat)
		mrg[tag].cur = cur
		
		local i
		for i=1,total do
			if mrg[tag].dat[i] and i==mrg[tag].cur + 1 then
				append(mrg[tag].pth,mrg[tag].dat[i])
				mrg[tag].dat[i] = nil
				mrg[tag].cur = i
			end
		end
	else
		mrg[tag].dat[cur] = dat
	end
	log.info("split.merge2",mrg[tag].cur,total)
	if mrg[tag].cur == total then
		local name = mrg[tag].pth
		clr(tag)
		return name
	else
		mrg[tag].expire = 10
		log.info("split.merge3",sys.timer_is_active(timerfnc))
		if not sys.timer_is_active(timerfnc) then
			sys.timer_loop_start(timerfnc,1000)
		end
	end
end
